package com.yejiali.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yejiali.backend.common.constants.RoleConstants;
import com.yejiali.backend.entity.MyUserDetails;
import com.yejiali.backend.entity.User;
import com.yejiali.backend.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author:yejiali
 * @Date:2025/5/10-05-10-17:09
 * @Decsription:com.yejiali.backend.service.impl
 * @Version:1.0
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,username);
        User user = userMapper.selectOne(queryWrapper);
        //判断是否有该用户
        if(user == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        //封装用户信息和权限信息
        MyUserDetails myUserDetails = new MyUserDetails(user,getAuthorities(user));
        //将信息封装为UserDetails返回
        return myUserDetails;
    }

    //获取用户角色并转换为GrantedAuthority
    private Collection<? extends GrantedAuthority> getAuthorities(User user) {
        List<GrantedAuthority> authorities = new ArrayList<>();
        //获取用户权限
        Integer role = user.getRole();
        if (role == RoleConstants.ADMIN) {
            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN")); // 2 管理员
        } else if(role== RoleConstants.AUDITOR_SUPER){
            authorities.add(new SimpleGrantedAuthority("ROLE_SUPER_AUDITOR")); // 1 复审员
        } else {
            authorities.add(new SimpleGrantedAuthority("ROLE_AUDITOR")); // 0 初审员
        };
        return authorities;
    }
}
